/**
 * @brief A serial library for basic setup and read/write abilities for
 * the UART.
 *
 * @file serial.c
 *
 * @author Robert Breznak, Peter Kalauskas
 * @date April 4, 2009
 */
#include "serial.h"
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdlib.h>
#include <stdarg.h>

/**
 * Initialize the UART for communication with a profile 8N1
 *
 * @return void
 * @author Robert Breznak, Peter Kalauskas
 */
void init_serial(void) {
	// set the baudrate
	UBRR0 = (uint16_t) UART_BSCALE;

	// enable tx/rx
	UCSR0B = (1 << RXCIE0) | (1 << TXEN0) | (1 << RXEN0);

	// set framing to 8N1
	UCSR0C = (1 << UCSZ00) | (1 << UCSZ01);

	sei();
}

/**
 * @fn void send_byte(uint8_t value)
 * Send a byte down the UART once the buffer has been cleared
 *
 * @param value the byte to be sent.
 * @return void
 * @author Robert Breznak
 */
void send_byte(uint8_t value) {
	// clear out the buffer before sending
	while (!(UCSR0A & (1 << UDRE0))) {
		// wait
	}

	// write value to the UART buffer
	UDR0 = value;
}

/**
 * @fn void send_bytes(uint8_t *data, uint8_t length)
 * Send an array of bytes down the UART once the buffer has been cleared
 *
 * @param data the array of bytes to be sent.
 * @param length the length of the array of bytes.
 * @return void
 * @author Peter Kalauskas
 */
void send_bytes(uint8_t *data, uint8_t length) {
	int i;

	for (i = 0; i < length; i++) {
		send_byte(*data);
		data++;
	}
}
